//
//  BuyingalistViewController.swift
//  NewLndd
//
//  Created by 邵禹曦 on 2020/1/3.
//  Copyright © 2020 辽宁当代. All rights reserved.
//

import UIKit
// MARK: - 买挂单 : 1 卖挂单 : 2
class BuyingalistViewController: HomeApiViewController, UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var TableView: UITableView!
    var Product : Allproducts?
    var pickup = pickUp()
    // Title
    @IBOutlet weak var gdTitle: UILabel!
    // 定义空数组
    var newsArray : NSArray = []
    // 定义数组  Use of undeclared type 'Status'  数组 : [模型Model]
    private lazy var ViewModels : [Buyingalist] = [Buyingalist]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        showInfo()
    }
    
}


// MARK: - 用户验证
extension BuyingalistViewController {
    private func showInfo() {
        // GCD
        let group = DispatchGroup()
 
        // 从沙盒中获取参数
         var userPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
         userPath =  (userPath as NSString).appendingPathComponent("data.plist")
         user = NSKeyedUnarchiver.unarchiveObject(withFile: userPath) as? User
        
        Thread.sleep(forTimeInterval: 0.05)


        // 用户验证
        self.u = user?.U!
        self.retcode = user?.RETCODE!
        // 用户验证
        let str = [u,"101",retcode]
         
        //self.isLogin = self._network(str: str as! [String], group: group)
        group.enter()
        NetworkTools.share.check_user(code: str as Array<Any>) { (result, error) in
                      
                          if error != nil {
                              print("no no no")
                              return
                          }
                          

                          if Int(self._retcode(res: result!))! < 0 {
                              self.isLogin = false
                          } else {
                              self.isLogin = true
                          }
                          group.leave()
                      }

        group.notify(queue: DispatchQueue.main) {
            if !self.isLogin {
                return self.setupVisitorView()
            } else {
                Thread.sleep(forTimeInterval: 0.05)
                // 2.设置导航栏内容
                self.setupNavigationBar()
                self.tableShouInfo()
            }
         }
    }
}

// MARK: - 设置UI界面
extension BuyingalistViewController {
    private func setupNavigationBar() {
        
        let sta = Product?.sta!
        if sta == "1" {
            gdTitle.text = "买挂单"
        } else {
            gdTitle.text = "卖挂单"
        }
    }
}



// MARK: - TableView
extension BuyingalistViewController {
    
    // MARK: - TableViewShowInfo
    @objc private func tableShouInfo() {
        
        let str = [self.Product!.COI!,self.Product!.sta!,"1","20",self.Product!.st]
        
        NetworkTools.share.my_pending_order_query(code: str as Array<Any>) { (result, error) in
            
            if error != nil {
                print("no no no")
                return
            }

            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
            print(resultArray)
            
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULT"] as? [String : AnyObject]   {
                    let code : Int = Int(arr["RETCODE"] as! String)!
                    if(Int(truncating: NSNumber(value: code)) < 0) {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "数据加载失败")
                            return self.setupVisitorView()
                        }
                    }
                }
            }
            
            // 跑一下数据
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let resultList = REP["RESULT"] as? [String : AnyObject] {
                    if let da : String = (resultList["DA"] as? String) {
                        if #available(iOS 13.0, *) {
                            for temp in self.getDictionaryFromJSONString(jsonString: da) {
                                let sta = Buyingalist(dict: temp as! [String : AnyObject] )
                                self.ViewModels.append(sta)
                                print(temp)
                            }
                        }
                        // 刷新表格
                        self.TableView.reloadData()
                    }
                }
            }
        }
    }
    
    
    // 行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.ViewModels.count
    }
    
    // 每行显示的数据
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : BuyingalistViewCell = tableView.dequeueReusableCell(withIdentifier: "BuyingalistViewCellid") as! BuyingalistViewCell
        cell.ViewModel = ViewModels[indexPath.row]
        
        // 尝试搞按钮
        cell.tj.tag = indexPath.row
        cell.tj.addTarget(self, action: #selector(ceBtn), for: .touchUpInside)
        return cell
    }
    
    // cell高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 260
    }
    
    // 是不是跳转绑定view了，数过不去
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //self.table.deselectRow(at: indexPath, animated: true)
        // prepare 传参
        //self.performSegue(withIdentifier: "seleszd", sender: indexPath)
    }
    
    // 每行绑定的button
    @objc private func ceBtn(sender: UIButton!) {

        self.pickup.COI = self.Product!.COI
        self.pickup.CON = self.Product!.CON
        self.pickup.ON = self.ViewModels[sender.tag].ON
        self.pickup.OP = self.ViewModels[sender.tag].OP
        self.pickup.OQ = self.ViewModels[sender.tag].OQ
        self.pickup.SQ = self.ViewModels[sender.tag].SQ
        self.pickup.BI = self.ViewModels[sender.tag].BI
        self.pickup.OT = self.ViewModels[sender.tag].OT
        self.performSegue(withIdentifier: "seleszd", sender: self.pickup)
        
    }
    
    // MARK: - 跳转并传参
    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {

        
        if segue.identifier == "seleszd" {
            let secVB = segue.destination as! pickUpViewController
            self.pickup.sta = "2"
            secVB.pickUp = self.pickup
        }
    }
    
}
